package com.yanzu.module.member.service.iot;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanzu.module.member.dal.dataobject.storeinfo.StoreInfoDO;
import com.yanzu.module.member.dal.mysql.storeinfo.StoreInfoMapper;
import com.yanzu.module.member.forest.SmyooClient;
import com.yanzu.module.member.service.iot.smyoo.SmyooQuerymcuidsReqVO;
import com.yanzu.module.member.service.iot.smyoo.SmyooSetdevicedataReqVO;
import com.yanzu.module.member.service.iot.smyoo.SmyooSynloginopenReqVO;
import com.yanzu.module.member.service.iot.smyoo.SmyooSynloginticketReqVO;
import com.yanzu.module.member.service.iot.ttlockBean.TTLockTokenReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.yanzu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yanzu.module.member.enums.ErrorCodeConstants.*;

@Slf4j
@Component
public class SmyooService {

    @Resource
    private SmyooClient smyooClient;

    @Value("${smyoo.clientId}")
    private String clientId;

    @Value("${smyoo.clientSecret}")
    private String clientSecret;

    @Value("${smyoo.deviceId}")
    private String deviceId;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private StoreInfoMapper storeInfoMapper;

    private final String redis_key = "smyoo.token_%s";

    public String getToken(Long storeId) {
        String key = String.format(redis_key, storeId);
        if (stringRedisTemplate.hasKey(key)) {
            return stringRedisTemplate.opsForValue().get(key);
        } else {
            //查出用户名和密码
            StoreInfoDO storeInfoDO = storeInfoMapper.selectById(storeId);
            if (ObjectUtils.isEmpty(storeInfoDO.getSmyooUsername()) || ObjectUtils.isEmpty(storeInfoDO.getSmyooPassword())) {
                throw exception(SMYOO_USER_NOT_FOUND);
            }
            SmyooSynloginopenReqVO smyooSynloginopenReqVO = new SmyooSynloginopenReqVO();
            smyooSynloginopenReqVO.setClient_id(clientId);
            smyooSynloginopenReqVO.setClient_secret(clientSecret);
            smyooSynloginopenReqVO.setDeviceId(deviceId);
            smyooSynloginopenReqVO.setPhone(storeInfoDO.getSmyooUsername());
            smyooSynloginopenReqVO.setPassword(storeInfoDO.getSmyooPassword());
            JSONObject synloginopen = smyooClient.synloginopen(smyooSynloginopenReqVO);
            if (synloginopen.getInteger("resultCode") != 0) {
                throw exception(SMYOO_AUTH_ERROR);
            } else {
                String autokey = synloginopen.getJSONObject("data").getString("autokey");
                String ticket = synloginopen.getJSONObject("data").getString("ticket");
                Integer cookieExpireTime = synloginopen.getJSONObject("data").getInteger("cookieExpireTime");
                SmyooSynloginticketReqVO smyooSynloginticketReqVO = new SmyooSynloginticketReqVO();
                smyooSynloginticketReqVO.setClient_id(clientId);
                smyooSynloginticketReqVO.setTicket(ticket);
                smyooSynloginticketReqVO.setDeviceId(deviceId);
                JSONObject synloginticket = smyooClient.synloginticket(smyooSynloginticketReqVO);
                if (synloginticket.getInteger("resultCode") != 0) {
                    throw exception(SMYOO_AUTH_ERROR);
                } else {
                    String BpeSessionId = synloginticket.getJSONObject("data").getString("BpeSessionId");
                    stringRedisTemplate.opsForValue().set(key, BpeSessionId, 23, TimeUnit.HOURS);
                    return BpeSessionId;
                }
            }

        }
    }

    public String queryMcuId(Long storeId, String name) {
        name = name.trim();
        String token = getToken(storeId);
        SmyooQuerymcuidsReqVO reqVO = new SmyooQuerymcuidsReqVO();
        reqVO.setClient_id(clientId);
        reqVO.setClient_secret(clientSecret);
        reqVO.setDeviceId(deviceId);
        reqVO.setBpeSessionId(token);
        reqVO.setMcuname(name);
        JSONObject querymcuids = smyooClient.querymcuids(reqVO, token);
        if (querymcuids.getInteger("resultCode") != 0) {
            throw exception(DEVICE_NOT_FOUND);
        } else {
            JSONArray array = querymcuids.getJSONObject("data").getJSONArray("mcuids");
            if (array.size() == 0) {
                throw exception(DEVICE_NOT_FOUND);
            }
            return array.getJSONObject(0).getString("mcuid");
        }
    }


    public void opSwitch(Long storeId, String mcuid, Integer status) {
        String token = getToken(storeId);
        SmyooSetdevicedataReqVO reqVO = new SmyooSetdevicedataReqVO();
        reqVO.setClient_id(clientId);
        reqVO.setClient_secret(clientSecret);
        reqVO.setDeviceId(deviceId);
        reqVO.setBpeSessionId(token);
        reqVO.setMcuid(mcuid);
        reqVO.setDatapoint("{\"status\":" + status + "}");
        JSONObject setdevicedata = smyooClient.setdevicedata(reqVO, token);
        if (setdevicedata.getInteger("resultCode").compareTo(-10215046) == 0) {
            throw exception(SMYOO_DEVICE_OFFLINE_ERROR);
        } else if (setdevicedata.getInteger("resultCode") != 0) {
            throw exception(DEVICE_OPTION_ERROR, setdevicedata.getString("resultMsg"));
        }
    }


    public void runSound(Long storeId, String mcuid, String type, Integer sound) {
        String token = getToken(storeId);
        SmyooSetdevicedataReqVO reqVO = new SmyooSetdevicedataReqVO();
        reqVO.setClient_id(clientId);
        reqVO.setClient_secret(clientSecret);
        reqVO.setDeviceId(deviceId);
        reqVO.setBpeSessionId(token);
        reqVO.setMcuid(mcuid);
        JSONObject data = new JSONObject();
        String str = "";
        switch (type) {
            case "1":
                str = "欢迎您光临,本店无人值守,需要帮助请联系客服，请您文明娱乐,禁止从事赌博等违法行为.祝您玩的开心！";
                break;
            case "2":
                str = "您的订单剩余时间已不足三十分钟,到期后将自动关闭房间电源,请您及时进行续费,避免影响使用！";
                break;
            case "3":
                str = "您的订单剩余时间已不足十五分钟,到期后将自动关闭房间电源,请您及时进行续费,避免影响使用！";
                break;
            case "4":
                str = "您的订单剩余时间已不足五分钟,到期后将自动关闭房间电源,请您及时进行续费,避免影响使用！";
                break;
            case "5":
                str = "尊敬的顾客您好,根据城市管理条例要求,请您在深夜消费时,注意控制噪音,以免影响到他人,感谢您的支持与理解！";
                break;
            case "6":
                str = "您的订单已到期,请您带好随身物品,欢迎下次光临！";
                break;
            default:
                str = "这是一条默认播放的文字";
                break;
        }
        data.put("text", str);
        data.put("spd", 6);
        data.put("pit", 6);
        data.put("vol", sound);
        data.put("per", 0);
        reqVO.setDatapoint(data.toJSONString());
        JSONObject setdevicedata = smyooClient.speakerplaylongtext(reqVO, token);
        if (setdevicedata.getInteger("resultCode").compareTo(-10215046) == 0) {
            throw exception(SMYOO_DEVICE_OFFLINE_ERROR);
        } else if (setdevicedata.getInteger("resultCode") != 0) {
            throw exception(DEVICE_OPTION_ERROR, setdevicedata.getString("resultMsg"));
        }
    }


}
